package com.stone.framework.common.client;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.stone.framework.core.cache.BasicConstant;
import com.stone.framework.message.ReqMessage;
import com.stone.framework.message.ResMessage;

import feign.hystrix.FallbackFactory;

@FeignClient(name = "stone-basic-service", fallbackFactory = BasicClient.UserFallbackFactory.class)
public interface BasicClient {

    Logger LOGGER = LoggerFactory.getLogger(BasicClient.class);

    @RequestMapping(value = "/param/business/getValue", method = RequestMethod.POST)
    ResMessage<String> getValue(ReqMessage<String> reqMessage);

    @RequestMapping(value = "/dict/member/getKV", method = RequestMethod.POST)
    ResMessage<Map<String, String>> getKV(ReqMessage<String> reqMessage);

    @Cacheable(value = BasicConstant.PREFIX_BUSINESS_PARAM, key = "#key", unless = "#result == null")
    default String getValue(String key) {
        ResMessage<String> resMessage = this.getValue(ReqMessage.build(key));
        return resMessage.getBody();
    }

    @Cacheable(value = BasicConstant.PREFIX_DICT_KV, key = "#code", unless = "#result == null")
    default Map<String, String> getKV(String code) {
        ResMessage<Map<String, String>> resMessage = this.getKV(ReqMessage.build(code));
        return resMessage.getBody();
    }

    @Component
    public static class UserFallbackFactory implements FallbackFactory<BasicClient> {

        @Override
        public BasicClient create(Throwable cause) {
            return new BasicClient() {

                @Override
                public ResMessage<String> getValue(ReqMessage<String> reqMessage) {
                    LOGGER.error("getValue()调用异常", cause);
                    return ResMessage.success(null);
                }

                @Override
                public ResMessage<Map<String, String>> getKV(ReqMessage<String> reqMessage) {
                    LOGGER.error("getKV()调用异常", cause);
                    return ResMessage.success(null);
                }

            };
        }

    }

}
